package com.a01_2021.thousandstimes.saas.controller;

import com.a01_2021.thousandstimes.exception.CustomException;
import com.a01_2021.thousandstimes.saas.service.AuthorizationService;
import com.a01_2021.thousandstimes.utils.AjaxResponse;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author FRQ
 * @since 2021-02-22
 */
@RestController
@RequestMapping("/authorization")
public class AuthorizationController {

    @Resource
    AuthorizationService authorizationService;

    /**
     * 通过用户ID查询是否授权
     * @param instanceId 访问实例id
     * @param userId     被查询用户ID
     * @return 返还AjaxResponse
     * @throws CustomException 抛出自定义异常
     */
    @PreAuthorize("hasAuthority('authorization-getAuthorizedFromUserId')")
    @DS("#header.instanceid")
    @PostMapping("/getAuthorizedFromUserId")
    public AjaxResponse getAuthorizedFromUserId(@RequestHeader(name = "instanceid") String instanceId, long userId) throws CustomException {
        if(StringUtils.isEmpty(instanceId)||!instanceId.equals("master")){
            return AjaxResponse.error("该接口只允许SAAS后台系统调用");
        }
        return AjaxResponse.success(authorizationService.getAuthorizedFromUserId(userId));
    }

    /**
     * 通过用户ID授权信息共享
     * @param instanceId 访问实例id
     * @param userId    授权用户ID
     * @return CustomException 抛出自定义异常
     */
    @PreAuthorize("hasAuthority('authorization-authorization')")
    @DS("#header.instanceid")
    @PostMapping("/authorization")
    public AjaxResponse authorization(@RequestHeader(name = "instanceid") String instanceId, long userId) throws CustomException {
        if(StringUtils.isEmpty(instanceId)||!instanceId.equals("master")){
            return AjaxResponse.error("该接口只允许SAAS后台系统调用");
        }
        return AjaxResponse.success(authorizationService.authorization(userId));
    }
}
